Parse.Cloud.define('createQlAccount', async (req, res) => {
  const { userId } = req.params
  if (!userId) {
    return res.error('请先登录')
  }

  try {
    const user = await new Parse.Query(Parse.User).equalTo('objectId', userId).first()
    if (!user) {
      return res.error('没有该用户')
    }

    const current = await new Parse.Query('QlAccount').equalTo('user', user).first()

    if (current) {
      return res.success({
        freeCount: current.get('freeCount')
      })
    }

    const config = await Parse.Config.get()
    const freeCount = config.get('freeCount')

    const account = new Parse.Object('QlAccount')
    await account.save({
      user,
      freeCount
    })

    res.success({
      freeCount
    })
  } catch (err) {
    console.log(err)
    res.error(err.message)
  }
})
